import { Player } from "@minecraft/server";
import { PlayerGroup } from "./PlayerGroup";

export class PlayerGroupManager {
  player_groups: Map<string, PlayerGroup>;

  constructor() {
    this.player_groups = new Map<string, PlayerGroup>();
  }

  public addGroup(id: string) {
    const group = new PlayerGroup(id);
    if (!this.player_groups.has(id)) this.player_groups.set(id, group);

    return group;
  }

  public delGroup(id: string) {
    this.player_groups.delete(id);
    return this;
  }

  public getGroup(id: string) {
    return this.player_groups.get(id);
  }

  public addPlayer(id: string, player: Player) {
    this.player_groups.get(id)?.addPlayer(player);
    return this;
  }

  public delPlayer(id: string, player: Player) {
    this.player_groups.get(id)?.delPlayer(player);
    return this;
  }

  public containsPlayer(player: Player): boolean {
    // debug.log(`${JSON.stringify(this.get_all_players())}`);
    return this.getAllPlayers().has(player);
  }

  public groupContainsPlayer(id: string, player: Player) {
    return this.getGroup(id)?.contains(player);
  }

  public getAllPlayers() {
    let result = new Set<Player>();
    this.player_groups.forEach((ele) => {
      const players = ele.getPlayers();
      if (players != undefined)
        players.forEach((ele) => {
          result.add(ele);
        });
    });
    return result;
  }

  public getAllGroupIds() {
    let result: string[] = [];
    for (let [, group] of this.player_groups) {
      result.push(group.id);
    }
    return result;
  }

  public free() {
    this.player_groups.forEach((ele) => {
      ele.free();
    });
  }
}
